import socket
import threading
class S():
    def __init__(self):
        self.A_dct = {}

    def accept_A(self,port):
        server = socket.socket()#创建服务器
        address = ('10.10.10.60',port)#连接本地ip,端口
        server.bind(address)#捆绑地址
        server.listen(10)#准许连接10个客户端
        print('服务器已启动')
        while 1:
            A_socket, addr = server.accept()#接受2个参数,地址和客户端服务器
            print(A_socket, addr)
            A_socket.send("欢迎来自{}的朋友,请输入你的姓名".format(str(addr)).encode("utf-8"))
            while 1:
                A_name = A_socket.recv(1024).decode("utf-8")
                if A_name in self.A_dct:
                    A_socket.send("用户名已经重复请重新输入".format(str(addr)).encode("utf-8"))
                else:
                    A_socket.send("欢迎名字是:{}的朋友加入群聊".format(A_name).encode("utf-8"))
                    self.A_dct[A_name] = A_socket
                    break
            for key, value in self.A_dct.items():
                value.send("欢迎{}加入群聊".format(A_name).encode("utf-8"))

            threading.Thread(target=self.send_receive, args=(A_name, A_socket, addr)).start()

    def send_receive(self, username, chanel, address):
        while 1:
            from_msg = chanel.recv(1024).decode("utf-8")
            print("收到来自{}-{}的消息:{}".format(username, str(address), from_msg))
            if str(from_msg).startswith("@"):
                msg_list = from_msg.split(" ")
                private_name = msg_list[0][1:].strip()
                print("private_name:{}".format(private_name))
                private_msg = msg_list[1]
                private_chanel = self.find_chanel(private_name)
                if private_chanel != None:
                    private_chanel.send("{}私聊你:{}".format(username, private_msg).encode("utf-8"))
                else:
                    chanel.send("你私聊的用户:{}不存在".format(private_name).encode("utf-8"))
            else:
                for key, value in self.client_dct.items():
                    value.send("{}对所有人说:{}".format(username, from_msg).encode("utf-8"))


    def find_chanel(self, username):
        for key, value in self.A_dct.items():
            if key == username:
                return value
        else:
            return None

if __name__ == '__main__':
    ts = S()
    ts.accept_A(9669)
